const mysql = require('mysql2');
const { Sequelize, DataTypes } = require('sequelize');

//创建与MySQL数据库的连接：
const sequelize = new Sequelize(${mysqldb.database}, ${mysqldb.username}, ${mysqldb.password}, {
  host: ${mysqldb.host},
  port: ${mysqldb.port},
  dialect: 'mysql',
});

//您可以通过检查 Promise 对象的状态码来确定数据库连接的状态。以下是一个示例代码：
sequelize.authenticate()
  .then(() => {
    console.log('数据库连接成功');
  })
  .catch((error) => {
    console.error('无法连接到数据库:', error);
  })
  .finally(() => {
    console.log('数据库连接状态:', sequelize.connectionManager.state);
  });

//定义请求和响应报文的模型（表结构）：
const wsapilogSchema = Sequelize.define('Request', {
  id: {
    type: DataTypes.STRING,
    primaryKey: true,
    autoIncrement: true,
  },
  fullUrl: {
    type: DataTypes.STRING,
    allowNull: false,
  },
  method: {
    type: DataTypes.STRING,
    allowNull: false,
  },
  url: {
    type: DataTypes.STRING,
    allowNull: false,
  },
  host: {
    type: DataTypes.STRING,
    allowNull: false,
  },
  protocol: {
    type: DataTypes.STRING,
    allowNull: false,
  },
  path: {
    type: DataTypes.STRING,
    allowNull: false,
  },
  headers: {
    type: DataTypes.STRING,
    allowNull: false,
  },
  res_body: {
    type: DataTypes.JSON,
    allowNull: false,
  },
   res_headers: {
     type: DataTypes.STRING,
     allowNull: false,
   },
   req: {
     type: DataTypes.STRING,
     allowNull: false,
   },
  req_body: {
    type: DataTypes.JSON,
    allowNull: true,
  },
  req_params: {
    type: DataTypes.JSON,
    allowNull: true,
  },
  client_ip: {
    type: DataTypes.TEXT,
    allowNull: true,
  },
  create_time: {
    type: DataTypes.TEXT,
    allowNull: true,
  },
});

//同步模型与数据库表：
wsapilogSchema.sync();
//这将确保模型与数据库表的结构保持同步。可以在应用程序初始化阶段调用此方法。

//将请求报文保存到数据库表：
const saveRequestResponse = (req, res) => {
  const { url, method, headers, body } = req;
  const { response } = res;

  wsapilogSchema.create({
    url,
    method,
    requestHeaders: JSON.stringify(headers),
    requestBody: body,
    responseHeaders: JSON.stringify(response.headers),
    responseBody: response.body,
  }).then((request) => {
    console.log('请求和响应报文已保存:', request.toJSON());
  }).catch((error) => {
    console.error('保存请求和响应报文时发生错误:', error);
  });
};

exports.sequelize=sequelize;
exports.wsapilogSchema=wsapilogSchema;
exports.mysql=mysql;
require('whistle').on('request', saveRequestResponse);
require('whistle').on('response',saveRequestResponse);
